/**
 * Created with IntelliJ IDEA.
 * User: 12629
 * Date: 2021/11/16
 * Time: 10:22
 * Description:
 */
public class HashBuck {

    static class Node {
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }
    private Node[] array = new Node[10];
    private int usedSize;
    private static final double DEFAULT_LOAD_FACTOR = 0.75;

    public void push(int key,int val) {
        Node node = new Node(key,val);
        int index = key % array.length;
        Node cur = array[index];
        while ( cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //cur == null;
        node.next = array[index];
        array[index] = node;
        this.usedSize++;

        if(loadFactor() >= DEFAULT_LOAD_FACTOR) {
            //扩容
            resize();
        }

    }
    private double loadFactor() {
        return usedSize*1.0/array.length;
    }

    private void resize() {
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                int index = cur.key % newArray.length;//新数组的下标位置
                Node curNext = cur.next;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
